<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/4/10
 * Time: 12:01
 */

namespace plugin\admin\app\logic\novel;


use app\common\lib\Common;
use app\common\lib\Guzzle;
use app\common\lib\Spreadsheet;
use app\common\lib\TencentCos;
use app\exception\IndexException;
use app\model\douyin\CooperateAppidModel;
use plugin\admin\app\common\Constant;
use plugin\admin\app\exception\AdminException;
use plugin\admin\app\logic\BaseLogic;
use plugin\admin\app\model\banner\Banner;
use plugin\admin\app\model\novel\NovelBusinessModel;
use plugin\admin\app\model\novel\NovelChapterModel;
use plugin\admin\app\model\novel\NovelSpreadModel;
use support\Request;
use support\Response;

class ChapterLogic extends BaseLogic
{
    protected static $instance;

    public function __construct()
    {
        $this->model = new NovelChapterModel();
    }

    public static function getInstance()
    {
        //        if(is_object(self::$instance)){
//            return self::$instance;
//        }

        return new self();
    }

    public function select(Request $request): Response
    {
        //更新方案数量
        $this->updatePlanNums();

        $field = $request->input('field');
        if($field==false){
            $request->inputSet('field','created_at');
            $request->inputSet('order','desc');
        }

        $request->inputSet('isdel','0');
        return parent::select($request);
    }

    protected function formatNormal($items, $total): Response
    {
        $novelMap = $this->getListMapById(NovelSpreadModel::getInstance(),$items,'novel_sn','novel_sn');
        foreach($items as &$val){
            $val['title'] = isset($novelMap[$val['novel_sn']])?$novelMap[$val['novel_sn']]['title']:'';
            $analyzeContentAiCommand = $val['analyze_content_ai_command']??'';
            $batchPromptAiCommand = $val['batch_prompt_ai_command']??'';
            $originalContentAiCommand = $val['original_content_ai_command']??'';
            $contentPartsAiCommand = $val['content_parts_ai_command']??'';
            $contentPartsAiCommandOverseas = $val['original_content_ai_command_overseas']??'';
            $val['analyze_content_ai_command'] = !empty($analyzeContentAiCommand)?$analyzeContentAiCommand:config('param.analyze_content_ai_command');

            $val['batch_prompt_ai_command'] = !empty($batchPromptAiCommand)?$batchPromptAiCommand:getAiCommand('batch_prompt_ai_command');
            $val['original_content_ai_command'] = !empty($originalContentAiCommand)?$originalContentAiCommand: getAiCommand('original_content_ai_command');
            $val['content_parts_ai_command'] = !empty($contentPartsAiCommand)?$contentPartsAiCommand: getAiCommand('content_parts_ai_command');
            $val['original_content_ai_command_overseas'] = !empty($contentPartsAiCommandOverseas)?$contentPartsAiCommandOverseas: getAiCommand('original_content_ai_command_overseas');
        }
        return parent::formatNormal($items, $total);
    }

    /**
     * 格式化下拉列表
     * @param $items
     * @return Response
     */
    protected function formatSelect($items): Response
    {
        $novelMap = $this->getListMapById(NovelSpreadModel::getInstance(),$items,'novel_sn','novel_sn');
        $formatted_items = [];
        foreach ($items as $item) {
            if($item['spread_type']==3 && empty($item['content'])){
                continue;
            }elseif($item['spread_type']!=3 && empty($item['prompt_content'])){
                continue;
            }

            $title = isset($novelMap[$item['novel_sn']])?$novelMap[$item['novel_sn']]['title']:'';
            $formatted_items[] = [
                'name' => '('.$title.') '.($item->name ?? $item->id).'('.$item->lang.')',
                'value' => $item->id
            ];
        }
        return  json(['code' => 0, 'msg' => 'ok', 'data' => $formatted_items]);
    }

    public function insert(Request $request): Response
    {
        if(empty($request->input('name'))){
            throw new IndexException(4020,'章节名称不能为空');
        }
        if(empty($request->input('number'))){
            throw new IndexException(4020,'段落序号不能为空');
        }
        if(empty($request->input('content'))){
            throw new IndexException(4020,'创作章节不能为空');
        }
        return parent::insert($request);
    }

    protected function doInsert(array $data)
    {
        $data['lang'] = NovelSpreadModel::getInstance()->getWhere(['novel_sn'=>$data['novel_sn']])->value('lang');
        $data['spread_type'] = NovelSpreadModel::getInstance()->getWhere(['novel_sn'=>$data['novel_sn']])->value('spread_type');
        $id = parent::doInsert($data);

        return $id;
    }

    public function update(Request $request): Response
    {
        if($request->input('status')===null){
            if(empty($request->input('name'))){
                throw new IndexException(4020,'章节名称不能为空');
            }
            if(empty($request->input('number'))){
                throw new IndexException(4020,'段落序号不能为空');
            }
            if(empty($request->input('content'))){
                throw new IndexException(4020,'创作章节不能为空');
            }
        }

        return parent::update($request);
    }
    protected function doUpdate($id, $data)
    {
        if(!empty($data['chapterid'])){
            $data['lang'] = NovelSpreadModel::getInstance()->getWhere(['novel_sn'=>$data['novel_sn']])->value('lang');
            $data['spread_type'] = NovelSpreadModel::getInstance()->getWhere(['novel_sn'=>$data['novel_sn']])->value('spread_type');
        }

        return parent::doUpdate($id, $data);
    }

    public function delete(Request $request): Response
    {
        return parent::isDelete($request);
    }

    public function aiRegenerate(Request $request): Response
    {
        set_time_limit(0);
        if($request->input('type')=='original_content_analyze'){
            if(empty($request->input('original_content'))){
                throw new AdminException(4020,'原文不能为空');
            }
            if(empty($request->input('original_content_ai_command'))){
                throw new AdminException(4020,'分析原文AI指令不能为空');
            }

            $replaceStr =  ["\r",'`','~','@','#','$','^','&','*','(',')','=','|','{','}','\\','[',']','<','>',
                            '《','》','/','￥','……','（','）','――','【','】','‘','”', '“','"','\'',' ','「','」'];
            $contentText = str_replace($replaceStr,"",$request->input('original_content'));

            $content = Common::generatedContent($contentText,$request->input('original_content_ai_command'));


            $contents = array_values(array_filter(explode("\n",$content)));

            return $this->json('0','ok',['analyze_content'=>$content,'analyze_nums'=>count($contents)]);

        }elseif($request->input('type')=='original_content_analyze_overseas'){
            if(empty($request->input('original_content'))){
                throw new AdminException(4020,'原文不能为空');
            }
            if(empty($request->input('original_content_ai_command_overseas'))){
                throw new AdminException(4020,'分析原文AI指令不能为空');
            }

            $replaceStr =  ["\r",'`','~','@','#','$','^','&','*','(',')','=','|','{','}','\\','[',']','<','>',
                            '《','》','/','￥','……','（','）','――','【','】','‘','”', '“','"','\'',' ','「','」'];
            $contentText = str_replace($replaceStr,"",$request->input('original_content'));

            $content = Common::generatedContent($contentText,$request->input('original_content_ai_command_overseas'),$request->input('lang',''));


            $contents = array_values(array_filter(explode("\n",$content)));

            return $this->json('0','ok',['content'=>$content,'nums'=>count($contents)]);

        }elseif($request->input('type')=='analyze_content_parts'){
            if(empty($request->input('analyze_content'))){
                throw new AdminException(4020,'分析内容不能为空');
            }
            if(empty($request->input('content_parts_ai_command'))){
                throw new AdminException(4020,'分析原文AI指令不能为空');
            }

            $replaceStr =  ["\r",'`','~','@','#','$','^','&','*','(',')','=','|','{','}','\\','[',']','<','>',
                            '《','》','/','￥','……','（','）','――','【','】','‘','”', '“','"','\'',' ','「','」'];
            $contentText = str_replace($replaceStr,"",$request->input('analyze_content'));

            $content = Common::generatedContent($contentText,$request->input('content_parts_ai_command'));

            $contents = array_values(array_filter(explode("\n",$content)));
            foreach ($contents as $k=>$val){
                //如果没有中文过滤掉该片段
                $pattern = '/[\x{4e00}-\x{9fa5}]+/u';
                $res = preg_match_all($pattern, $val, $matches);
                if($res==false){
                    unset($contents[$k]);
                    continue;
                }
            }
            $content = implode("\n",$contents);

            return $this->json('0','ok',['content'=>$content,'part_nums'=>count($contents)]);

        }elseif($request->input('type')=='batch_regenerate_prompt'){
            if(empty($request->input('content'))){
                throw new AdminException(4020,'创作章节不能为空');
            }
            if(empty($request->input('batch_prompt_ai_command'))){
                throw new AdminException(4020,'AI指令不能为空');
            }
            if(empty($request->input('gptversion'))){
                throw new AdminException(4020,'GPT版本必选');
            }

            $replaceStr =  ["\r",'`','~','@','#','$','^','&','*','(',')','=','|','{','}','\\','[',']','<','>',
                            '《','》','/','￥','……','（','）','――','【','】','‘','”', '“','"','\'',' ','「','」'];
            $contents = str_replace($replaceStr,"",$request->input('content'));
            $contents = array_values(array_filter(explode("\n",preg_replace('/@[=]+@/',"\n",$contents))));

            $contentData = [];
            foreach ($contents as $k=>$content){
                $contentData[] = (($k+1).'.').preg_replace('/^\d+[\.]*/','',$content);
            }
            $contentText = implode("\n",$contentData);
            if($contentText==false){
                throw new AdminException(4020,'章节内容不能为空');
            }
            $batchPromptAiCommand = str_replace(['@parts'],[count($contentData)],$request->input('batch_prompt_ai_command'));

            $promptContent = Common::generatedBatchPrompt($contentText,$batchPromptAiCommand,$request->input('gptversion'));

            $promptContents = array_values(array_filter(explode("\n",$promptContent)));

            return $this->json('0','ok',['prompt_content'=>$promptContent,'part_nums'=>count($promptContents)]);
        }
    }
}